import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

const routerObj = {
  scrollBehavior: () => ({ y: 0 }),
  routes: []
}
const createRouter = () => new Router(routerObj)

const router = createRouter()

// 路由出错触发
router.onError((error) => {
  const reg = new RegExp('Loading chunk (\\d)+ failed', 'g')
  const isChunkLoadFailed = error.message.match(reg)
  if (isChunkLoadFailed) {
    window.location.reload()
    // router.replace(router.history.pending.fullPath);
  } else {
    console.error('router.onError: ', error)
  }
})

// Detail see: https://github.com/vuejs/vue-router/issues/1234#issuecomment-357941465
export function resetRouter () {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher // reset router
}

export default router
